import React, { useEffect, useState, Key } from 'react'
import { useParams, useNavigate } from 'react-router-dom'

import { Card, Row, Col, Tree, Tag, Pagination, Table, Button } from 'antd'
import type { DataNode, TreeProps } from 'antd/es/tree'
import {
  reqHospitalScheduleDep,
  regHospitalScheduleRule,
  reqHospitalScheduleList,
} from '@api/hospital/hospitalList'
import {
  IdepList,
  IbookScheduleList,
  IScheduleList,
} from '@api/hospital/model/hospitalListTypes'

const columns = [
  {
    title: '序号',
    render(a: any, b: any, index: number) {
      return index + 1
    },
  },
  {
    title: '职称',
    dataIndex: 'title',
  },
  {
    title: '号源时间',
    dataIndex: 'workDate',
  },
  {
    title: '可预约数',
    dataIndex: 'availableNumber',
  },
  {
    title: '剩余预约数',
    dataIndex: 'reservedNumber',
  },
  {
    title: '挂号费(元)',
    dataIndex: 'amount',
  },
  {
    title: '擅长技能',
    dataIndex: 'skill',
  },
]

//动态计算所有科室父盒子的高度
// 计算逻辑: 当前页面可视区的高度 - Header高度 - tabs高度 - Card的内边距 - 选择的高度- 外边距
const treeContainerHeight =
  document.body.clientHeight - 64 - 34 - 24 * 2 - 22 - 14

let depcode: Key // 当前科室的编码
export default function HospitalSchedule() {
  const navigate = useNavigate()
  const hoscode = useParams().hoscode as string

  // 所有的科室数据的状态
  const [depList, setDepList] = useState<IdepList>([])
  // 所有的一级科室的depcode的数组状态
  const [depCodeList, setDepCodeList] = useState<string[]>([])

  // 分页状态
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(50)

  //选择用到的状态
  const [hosname, setHosname] = useState('')
  const [depname, setDepname] = useState('')
  const [workDate, setWorkDate] = useState('')

  // 排班规则的状态
  const [scheduleRules, setScheduleRules] = useState<IbookScheduleList>([])

  // 排班列表的状态
  const [scheduleList, setScheduleList] = useState<IScheduleList>([])

  useEffect(() => {
    async function fetch() {
      // 获取当前医院科室数据
      // getDepList是一个异步函数,异步函数的返回值就是promise对象.当这个函数里面的所有代码执行完毕,则这个对应的promise的状态就会变成成功
      // 这个异步函数,返回值是什么,那么这个异步函数的promise成功之后的value值就是什么
      const result = await getDepList()
      // console.log(result)
      // result就是所有的科室数据,我们一打开页面要展示的是专科的多发硬化的科室的排班规则
      depcode = result[0].children[0].depcode

      const workDate = await getScheduleRules(page, pageSize, depcode)

      // 获取排班列表数据
      getScheduleList(workDate)
    }
    fetch()
  }, [])

  // 获取当前医院所有科室数据的函数
  const getDepList = async () => {
    // 获取hoscode
    const result = await reqHospitalScheduleDep(hoscode as string)
    // depCodeList是存放了所有一级科室的depcode的数组
    const depCodeList = result.map((item) => {
      // 返回一级科室的depcode
      return item.depcode
    })

    // 给所有的一级科室的数据对象,添加disabled:true.让一级科室禁用
    result.forEach((item) => {
      item.disabled = true
    })
    setDepCodeList(depCodeList)
    setDepList(result)

    // 给科室名称赋值
    setDepname(result[0].children[0].depname)

    return result
  }

  // 获取排班规则的数据
  const getScheduleRules = async (
    page: number,
    pageSize: number,
    depcode: Key
  ) => {
    const result = await regHospitalScheduleRule({
      page,
      limit: pageSize,
      hoscode,
      depcode,
    })
    console.log(result)
    setScheduleRules(result.bookingScheduleList)
    setTotal(result.total)
    setHosname(result.baseMap.hosname)

    // 修改workDate
    setWorkDate(
      result.bookingScheduleList[0] && result.bookingScheduleList[0].workDate
    )
    return (
      result.bookingScheduleList[0] && result.bookingScheduleList[0].workDate
    )
  }

  // 获取排班列表的数据
  const getScheduleList = async (workDate: string) => {
    const result = await reqHospitalScheduleList(hoscode, depcode, workDate)
    // console.log(result)
    setScheduleList(result)
  }

  // 选择树结构中某个节点,会触发这个函数
  const onSelect: TreeProps['onSelect'] = async (selectedKeys, info) => {
    // console.log('selected', selectedKeys, info)
    // 修改全局的depcode
    depcode = selectedKeys[0]

    const workDate = await getScheduleRules(1, pageSize, depcode)

    getScheduleList(workDate)
  }

  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>
      {/* 是antd中的栅格系统(Grid), Row表示一行, Col表示一列. Col的span表示这一类在一行中占多少份. 一行是24份 */}
      {/* gutter表示一行中,每一列之间的间隔.单位是px */}
      <Row gutter={20}>
        <Col span={5}>
          <div
            style={{
              border: '1px solid #ccc',
              height: treeContainerHeight,
              overflow: 'auto',
            }}
          >
            <Tree
              onSelect={onSelect} // 点击树结构中的某一个节点会触发的函数
              treeData={depList as []} // treeData表示树结构中展示的数据
              // Tree组件默认渲染treeData里面对象的title和key . 但是我们的数据中没有这两个字段,所以告诉Tree组件,应该渲染的是depname和depcode
              fieldNames={{
                title: 'depname',
                key: 'depcode',
              }}
              // 让树结构中,指定的某些节点展示的配置项
              expandedKeys={depCodeList}
            />
          </div>
        </Col>
        <Col span={19}>
          <div>
            {scheduleRules.map((item) => {
              return (
                <Tag
                  key={item.workDate}
                  color={item.workDate === workDate ? 'green' : ''}
                  onClick={() => {
                    // 要修改workDate
                    setWorkDate(item.workDate)
                    getScheduleList(item.workDate)
                  }}
                >
                  <div>
                    {item.workDate} {item.dayOfWeek}
                  </div>
                  <div>
                    {item.availableNumber} / {item.reservedNumber}
                  </div>
                </Tag>
              )
            })}
          </div>
          <Pagination
            current={page}
            pageSize={pageSize}
            total={total}
            style={{ marginTop: 10, marginBottom: 10 }}
            showSizeChanger={true}
            onChange={async (page, pageSize) => {
              setPage(page)
              setPageSize(pageSize)
              //点击分页,重新获取排班规则
              const workDate = await getScheduleRules(page, pageSize, depcode)
              getScheduleList(workDate)
            }}
          ></Pagination>

          <Table
            columns={columns}
            bordered
            dataSource={scheduleList}
            pagination={false}
            rowKey={'id'}
          ></Table>
          <Button
            style={{ marginTop: 20 }}
            onClick={() => {
              navigate(-1)
            }}
          >
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  )
}
